const questionElement = document.getElementById('question');
const answer1Element = document.getElementById('answer1');
const answer2Element = document.getElementById('answer2');
const answer3Element = document.getElementById('answer3');
const answer4Element = document.getElementById('answer4');
const scoreElement = document.getElementById('score');

let score = 0;

function loadScore() {
    const savedScore = localStorage.getItem('score');
    if (savedScore) {
        score = parseInt(savedScore);
    }
    scoreElement.textContent = `Счет: ${score}`;
}

function saveScore() {
    localStorage.setItem('score', score);
}

function generateQuestion() {
    let num1, num2, operator;

    do {
        num1 = Math.floor(Math.random() * 10) + 1;
        num2 = Math.floor(Math.random() * 10) + 1;
        operator = ['+', '-'][Math.floor(Math.random() * 2)];
    } while (eval(num1 + operator + num2) < 0 || eval(num1 + operator + num2) > 10);

    const correctAnswer = eval(num1 + operator + num2);
    const answers = [correctAnswer, incorrectAnswer(), incorrectAnswer(), incorrectAnswer()];

    // Shuffle the answers array
    for (let i = answers.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [answers[i], answers[j]] = [answers[j], answers[i]];
    }

    questionElement.textContent = `${num1} ${operator} ${num2} = ?`;

    answer1Element.textContent = answers[0];
    answer1Element.onclick = () => checkAnswer(answers[0], correctAnswer);

    answer2Element.textContent = answers[1];
    answer2Element.onclick = () => checkAnswer(answers[1], correctAnswer);

    answer3Element.textContent = answers[2];
    answer3Element.onclick = () => checkAnswer(answers[2], correctAnswer);

    answer4Element.textContent = answers[3];
    answer4Element.onclick = () => checkAnswer(answers[3], correctAnswer);
}

function incorrectAnswer() {
    let num1, num2, operator;

    do {
        num1 = Math.floor(Math.random() * 10) + 1;
        num2 = Math.floor(Math.random() * 10) + 1;
        operator = ['+', '-'][Math.floor(Math.random() * 2)];
    } while (eval(num1 + operator + num2) < 0 || eval(num1 + operator + num2) > 10);

    return eval(num1 + operator + num2);
}

function checkAnswer(answer, correctAnswer) {
    if (answer === correctAnswer) {
        score++;
    } else {
        score--;
    }

    scoreElement.textContent = `Счет: ${score}`;

    generateQuestion();
	
	saveScore();
}

loadScore();
generateQuestion();
